package com.atguigu.controller;

import com.atguigu.base.BaseController;
import com.atguigu.entity.Community;
import com.atguigu.entity.Dict;
import com.atguigu.service.CommunityService;
import com.atguigu.service.DictService;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/community")
public class CommunityController extends BaseController {
    @DubboReference
    private CommunityService communityService;
    @DubboReference
    private DictService dictService;

    @RequestMapping
    public String index(ModelMap modelMap, HttpServletRequest request) {
        Map<String, Object> filters = getFilters(request);
        modelMap.addAttribute("filters", filters);
        PageInfo<Community> page = communityService.findPage(filters);
        modelMap.addAttribute("page",page);
        //查询北京下的所有区域
        List<Dict> areaList= dictService.findListByDictCode("beijing");
        // 将areaList放入请求域
        modelMap.addAttribute("areaList",areaList);

        return "community/index";
    }


    /*
     * 渲染小区新增页面处理器
     * */
    @RequestMapping("/create")
    public String create(ModelMap modelMap) {
        //查询北京下的所有区域，将所有数据放入请求域
        List<Dict> areaList = dictService.findListByDictCode("beijing");
        modelMap.addAttribute("areaList",areaList);
        return "community/create";

    }
    /**
     * 定义一个存储新增Community数据进入数据的处理器
     * 渲染成功提示页
     */
    @PostMapping("/save")
    public String save(Community community){
        communityService.index(community);
        return "common/successPage";
    }
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id,ModelMap modelMap){
        Community community = communityService.getById(id);
        modelMap.addAttribute("community",community);
        List<Dict> areaList = dictService.findListByDictCode("beijing");
        modelMap.addAttribute("areaList",areaList);
        return "community/edit";
    }
    @PostMapping("/update")
    public String update(Community community){
        communityService.update(community);
        return "common/successPage";
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
        communityService.delete(id);
        return "redirect:/community";
    }
}
